use chrono::{DateTime, Duration, Local, NaiveDateTime, NaiveTime, TimeZone};
use log::{debug, info, warn};
use rand::{Rng, rng};
use std::time::Duration as StdDuration;
use tokio::time::interval;

use super::account_logger::AccountLogger;
use super::config::{Config, parse_time_string};
use super::execution_tracker::ExecutionTracker;
use super::task_manager::TaskManager as DayTaskManager;
use super::tasks::TaskManager;
use super::utils::{mask_proxy_url, mask_email};

/// 表示一天中的具体时间（时分秒）
#[derive(Debug, Clone, Copy)]
pub struct TimeSpec {
    pub hour: u32,
    pub minute: u32,
    pub second: u32,
}

impl TimeSpec {
    pub fn new(hour: u32, minute: u32, second: u32) -> Self {
        Self { hour, minute, second }
    }
    
    pub fn from_hour(hour: u32) -> Self {
        Self { hour, minute: 0, second: 0 }
    }
    
    pub fn to_naive_time(self) -> NaiveTime {
        NaiveTime::from_hms_opt(self.hour, self.minute, self.second)
            .unwrap_or_else(|| NaiveTime::from_hms_opt(self.hour, 0, 0).unwrap())
    }
}

use std::collections::HashMap;

pub struct AdvancedScheduler {
    execution_tracker: ExecutionTracker,
    day_task_manager: DayTaskManager,
    account_logger: AccountLogger,
    next_execution_at: Option<DateTime<Local>>,
    account_schedules: HashMap<String, DateTime<Local>>, // 每个账号的下次执行时间
    config_path: String, // 配置文件路径
}

#[allow(dead_code)]
struct ExecutionSummary {
    executed_any: bool,
    earliest_interval_retry: Option<DateTime<Local>>,
}

impl AdvancedScheduler {
    pub fn new() -> Self {
        Self {
            execution_tracker: ExecutionTracker::new(),
            day_task_manager: DayTaskManager::new(),
            account_logger: AccountLogger::new(),
            next_execution_at: None,
            account_schedules: HashMap::new(),
            config_path: "config.toml".to_string(), // 默认路径
        }
    }

    /// 设置配置文件路径
    pub fn set_config_path(&mut self, path: String) {
        self.config_path = path;
    }

    pub async fn run(&mut self, config: &Config) -> i32 {
        if let Err(e) = self.day_task_manager.load_all_counters(config).await {
            warn!("Failed to load persisted execution counters: {}", e);
        }

        // 初始化所有账号的日志文件
        self.initialize_account_logs(config);

        // 打印任务配置和状态
        self.show_task_configurations(config).await;
        self.show_progress().await;

        match config.schedule.mode.as_str() {
            "immediate" => {
                info!("Immediate mode: running all enabled tasks once");
                let summary = self.execute_all_tasks(config, true).await;
                if !summary.executed_any {
                    info!("Immediate mode finished with no runnable tasks");
                }
                info!("Immediate mode completed");
                0 // 正常退出
            }
            "auto" => {
                info!("Auto scheduling mode selected");
                self.next_execution_at = None;
                // 初始化每个账号的执行时间
                self.initialize_account_schedules(config);
                self.run_auto_schedule(config).await
            }
            _ => {
                warn!("Unknown execution mode: {}", config.schedule.mode);
                1 // 错误退出
            }
        }
    }

    async fn run_auto_schedule(&mut self, config: &Config) -> i32 {
        let mut ticker = interval(StdDuration::from_secs(60));
        info!("Auto scheduler loop started; checking every minute");

        // 启动配置文件监听
        let config_watcher = super::config_watcher::ConfigWatcher::new(self.config_path.clone());
        let mut reload_rx = config_watcher.start_watching();

        // 显示所有账号的初始执行时间
        self.log_all_account_schedules();

        loop {
            tokio::select! {
                // 配置文件变更信号
                Some(_) = reload_rx.recv() => {
                    info!("🔄 检测到配置文件变更,正在验证新配置...");
                    
                    match Config::from_file(&self.config_path) {
                        Ok(mut new_config) => {
                            if let Err(e) = new_config.validate() {
                                warn!("❌ 新配置验证失败,继续使用旧配置: {}", e);
                                continue;
                            }
                            
                            info!("✅ 新配置验证通过,准备重启程序以应用更改...");
                            
                            // 保存当前状态
                            if let Err(e) = self.day_task_manager.save_all_counters().await {
                                warn!("Failed to save counters before restart: {}", e);
                            }
                            
                            info!("💾 已保存执行状态");
                            info!("🔄 程序将在3秒后自动重启...");
                            
                            tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
                            
                            // 返回退出码100表示需要重启
                            return 100;
                        }
                        Err(e) => {
                            warn!("❌ 配置文件加载失败,继续使用旧配置: {}", e);
                        }
                    }
                }
                
                // 定时检查任务执行
                _ = ticker.tick() => {
                    let now = Local::now();

                    // 检查是否有账号需要执行
                    let accounts_to_execute: Vec<String> = self.account_schedules
                        .iter()
                        .filter(|(_, scheduled_time)| now >= **scheduled_time)
                        .map(|(key, _)| key.clone())
                        .collect();

                    if accounts_to_execute.is_empty() {
                        continue;
                    }

                    // 执行到期的账号
                    for account_key in accounts_to_execute {
                        info!("执行账号: {}", account_key);
                        self.execute_single_account(config, &account_key).await;
                        
                        // 更新该账号的下次执行时间
                        self.update_account_schedule(&account_key, config);
                        
                        // 将下次执行时间保存到counter文件
                        if let Some(next_time) = self.account_schedules.get(&account_key) {
                            self.day_task_manager.update_next_execution_time(&account_key, *next_time).await;
                        }
                    }

                    // 保存计数器
                    if let Err(e) = self.day_task_manager.save_all_counters().await {
                        warn!("Failed to persist execution counters: {}", e);
                    }
                    self.show_progress().await;
                }
            }
        }
    }

    /// 记录所有账号的调度时间
    fn log_all_account_schedules(&self) {
        info!("=== 账号执行计划 ===");
        let mut schedules: Vec<_> = self.account_schedules.iter().collect();
        schedules.sort_by_key(|(_, time)| *time);
        
        for (account_key, scheduled_time) in schedules {
            info!("  {} -> {}", account_key, scheduled_time.format("%Y-%m-%d %H:%M:%S"));
        }
        info!("==================");
    }

    /// 执行单个账号的任务
    async fn execute_single_account(&mut self, config: &Config, account_key: &str) {
        // 解析account_key获取任务名和账号昵称
        let parts: Vec<&str> = account_key.split(':').collect();
        if parts.len() != 2 {
            return;
        }
        
        let task_name = parts[0];
        let nickname = parts[1];
        
        // 找到对应的任务和账号配置
        for task_config in &config.tasks {
            if task_config.name != task_name || !task_config.enabled {
                continue;
            }
            
            for account in &task_config.accounts {
                if account.nickname != nickname || !account.enabled {
                    continue;
                }
                
                // 检查各种执行条件
                if !self.day_task_manager.can_execute_account(account_key, config, task_config, account).await {
                    self.account_logger.warn(account_key, "已达到总天数限制");
                    continue;
                }
                
                let (_, _, min_interval, min_executions, max_executions, _) = 
                    self.get_account_config(config, task_config, account);
                
                if !self.execution_tracker.can_execute_task(account_key, min_interval, min_executions, max_executions) {
                    if self.execution_tracker.has_reached_daily_limit(account_key, max_executions) {
                        self.account_logger.info(account_key, "今日已达到执行次数上限");
                    } else {
                        self.account_logger.info(account_key, "未到最小执行间隔");
                    }
                    continue;
                }
                
                // 执行任务
                if let Some(task) = TaskManager::get_task(&task_config.name) {
                    info!("Starting task {} for account {}", task_config.name, account.nickname);
                    
                    self.account_logger.info(account_key, &format!("开始执行任务: {}", task_config.name));
                    if let Some(proxy) = account.proxy.as_ref().or(task_config.proxy.as_ref()) {
                        self.account_logger.info(account_key, &format!("使用代理: {}", proxy));
                    }
                    
                    let result = task.execute(account, task_config.proxy.as_ref()).await;
                    
                    match result {
                        Ok(_) => {
                            info!("Task completed successfully: {} ({})", task_config.name, account.nickname);
                            self.account_logger.info(account_key, &format!("任务执行成功: {}", task_config.name));
                            
                            self.execution_tracker.record_execution(account_key);
                            self.day_task_manager.record_account_execution(account_key).await;
                        }
                        Err(e) => {
                            warn!("Task execution failed {} ({}): {}", task_config.name, account.nickname, e);
                            self.account_logger.error(account_key, &format!("任务执行失败: {} - {}", task_config.name, e));
                            
                            self.execution_tracker.record_execution(account_key);
                        }
                    }
                }
                
                return;
            }
        }
    }

    async fn execute_all_tasks(
        &mut self,
        config: &Config,
        immediate_mode: bool,
    ) -> ExecutionSummary {
        let mut executed_any = false;
        let mut earliest_interval_retry: Option<DateTime<Local>> = None;

        for task_config in &config.tasks {
            if !task_config.enabled {
                continue;
            }

            // 遍历所有账号
            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }

                let account_key = Config::get_account_key(&task_config.name, &account.nickname);

                // 检查天数限制
                if !self
                    .day_task_manager
                    .can_execute_account(&account_key, config, task_config, account)
                    .await
                {
                    continue;
                }

                // 获取账号的配置(优先级: 账号 > 任务 > 全局)
                let (start_time, end_time, min_interval, min_executions, max_executions, _fixed_executions) =
                    self.get_account_config(config, task_config, account);

                let current_time = Local::now();

                // 检查时间窗口
                if !immediate_mode {
                    let current_naive_time = current_time.time();
                    let start_naive_time = start_time.to_naive_time();
                    let end_naive_time = end_time.to_naive_time();
                    
                    if current_naive_time < start_naive_time || current_naive_time >= end_naive_time {
                        debug!(
                            "Account {} of task {} skipped; outside time window {:02}:{:02}:{:02}-{:02}:{:02}:{:02}",
                            account.nickname,
                            task_config.name, 
                            start_time.hour, start_time.minute, start_time.second,
                            end_time.hour, end_time.minute, end_time.second
                        );
                        continue;
                    }
                }

                // 检查执行频率
                if !self.execution_tracker.can_execute_task(
                    &account_key,
                    min_interval,
                    min_executions,
                    max_executions,
                ) {
                    if self
                        .execution_tracker
                        .has_reached_daily_limit(&account_key, max_executions)
                    {
                        debug!("Account {} of task {} hit the per-day execution limit", account.nickname, task_config.name);
                    } else if let Some(next_allowed) = self
                        .execution_tracker
                        .next_allowed_time(&account_key, min_interval)
                    {
                        if next_allowed > current_time {
                            earliest_interval_retry = match earliest_interval_retry {
                                Some(existing) if existing <= next_allowed => Some(existing),
                                _ => Some(next_allowed),
                            };
                            debug!(
                                "Account {} of task {} must wait until {} before executing",
                                account.nickname,
                                task_config.name,
                                next_allowed.format("%Y-%m-%d %H:%M:%S")
                            );
                        }
                    }
                    continue;
                }

                // 执行任务
                if let Some(task) = TaskManager::get_task(&task_config.name) {
                    info!("Starting task {} for account {}", task_config.name, account.nickname);
                    
                    // 记录到账号日志
                    self.account_logger.info(&account_key, &format!("开始执行任务: {}", task_config.name));
                    if let Some(proxy) = account.proxy.as_ref().or(task_config.proxy.as_ref()) {
                        self.account_logger.info(&account_key, &format!("使用代理: {}", proxy));
                    }
                    
                    let result = task.execute(account, task_config.proxy.as_ref()).await;

                    match result {
                        Ok(_) => {
                            info!("Task completed successfully: {} ({})", task_config.name, account.nickname);
                            self.account_logger.info(&account_key, &format!("任务执行成功: {}", task_config.name));
                            
                            self.execution_tracker.record_execution(&account_key);
                            self.day_task_manager
                                .record_account_execution(&account_key)
                                .await;
                            executed_any = true;
                        }
                        Err(e) => {
                            warn!("Task execution failed {} ({}): {}", task_config.name, account.nickname, e);
                            self.account_logger.error(&account_key, &format!("任务执行失败: {} - {}", task_config.name, e));
                            
                            self.execution_tracker.record_execution(&account_key);
                        }
                    }
                } else {
                    warn!("Unknown task requested: {}", task_config.name);
                    self.account_logger.error(&account_key, &format!("未知任务: {}", task_config.name));
                }
            }
        }

        if executed_any {
            if let Err(e) = self.day_task_manager.save_all_counters().await {
                warn!("Failed to persist execution counters: {}", e);
            }
            self.show_progress().await;
        }

        ExecutionSummary {
            executed_any,
            earliest_interval_retry,
        }
    }

    #[allow(dead_code)]
    fn get_execution_summary(&mut self, config: &Config) -> String {
        let mut summaries = Vec::new();
        
        for task_config in &config.tasks {
            if !task_config.enabled {
                continue;
            }
            
            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }
                
                let account_key = Config::get_account_key(&task_config.name, &account.nickname);
                let (_, _, _, min_exec, max_exec, _) = self.get_account_config(config, task_config, account);
                let today_count = self.execution_tracker.get_today_executions_count_public(&account_key);
                let today_target = self.execution_tracker.get_today_target(&account_key, min_exec, max_exec);
                
                summaries.push(format!("{}({}): {}/{}", task_config.name, account.nickname, today_count, today_target));
            }
        }
        
        if summaries.is_empty() {
            "无任务".to_string()
        } else {
            summaries.join(", ")
        }
    }

    async fn show_task_configurations(&mut self, config: &Config) {
        info!("========================================");
        info!("任务调度器启动");
        info!("========================================");
        
        let global_start = self.parse_global_start_time(config);
        let global_end = self.parse_global_end_time(config);
        
        info!("执行模式: {}", config.schedule.mode);
        info!("时间窗口: {:02}:{:02}:{:02} - {:02}:{:02}:{:02}", 
            global_start.hour, global_start.minute, global_start.second,
            global_end.hour, global_end.minute, global_end.second);
        
        if let Some(fixed) = config.schedule.fixed_executions_per_day {
            info!("每天固定执行 {} 次，间隔 {} 小时", fixed, config.schedule.min_interval_hours.unwrap_or(2));
        } else {
            info!("每天最多 {} 次，间隔 {} 小时", 
                config.schedule.max_executions_per_day.unwrap_or(3),
                config.schedule.min_interval_hours.unwrap_or(2));
        }
        
        if let Some(days) = config.schedule.total_days
            && days > 0
        {
            info!("总天数: {} 天", days);
        }
        info!("");
        
        for task_config in config.tasks.iter() {
            if !task_config.enabled {
                continue;
            }
            
            info!("任务: {}", task_config.name);
            if let Some(proxy) = &task_config.proxy {
                info!("  任务代理: {}", mask_proxy_url(proxy));
            }
            info!("");
            
            // 遍历所有账号
            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }
                
                let account_key = Config::get_account_key(&task_config.name, &account.nickname);
                let (start_time, end_time, min_interval, min_exec, max_exec, fixed_exec) = 
                    self.get_account_config(config, task_config, account);
                
                // 脱敏显示账号昵称(如果是邮箱)
                let display_nickname = if account.nickname.contains('@') {
                    mask_email(&account.nickname)
                } else {
                    account.nickname.clone()
                };
                info!("  账号: {}", display_nickname);
                if let Some(proxy) = &account.proxy {
                    info!("    代理: {}", mask_proxy_url(proxy));
                }
                info!("    时间: {:02}:{:02}:{:02}-{:02}:{:02}:{:02}, 间隔{}小时, 每天{}次",
                    start_time.hour, start_time.minute, start_time.second,
                    end_time.hour, end_time.minute, end_time.second,
                    min_interval,
                    if let Some(fixed) = fixed_exec { format!("固定{}", fixed) } else { format!("最多{}", max_exec) });
                
                // 总天数和进度
                let total_days = account.total_days
                    .or(task_config.total_days)
                    .or(config.schedule.total_days)
                    .unwrap_or(0);
                
                if total_days > 0 {
                    let progress = self.day_task_manager.get_all_progress().await;
                    if let Some((executed, _)) = progress.get(&account_key) {
                        let percentage = if total_days > 0 { (*executed * 100) / total_days } else { 0 };
                        info!("    进度: {}/{} 天 ({}%)", executed, total_days, percentage);
                    } else {
                        info!("    进度: 0/{} 天", total_days);
                    }
                }
                
                // 今日状态
                let today_count = self.execution_tracker.get_today_executions_count_public(&account_key);
                let today_target = self.execution_tracker.get_today_target(&account_key, min_exec, max_exec);
                info!("    今日: {}/{} 次 (范围: {}-{})", today_count, today_target, min_exec, max_exec);
                
                // 上次执行
                if let Some(last_time) = self.execution_tracker.get_last_execution_time(&account_key) {
                    let now = Local::now();
                    let elapsed = now - last_time;
                    
                    if elapsed.num_hours() < min_interval as i64 {
                        let wait_minutes = (min_interval as i64 * 60) - elapsed.num_minutes();
                        info!("    上次: {} 前, 还需等待 {} 分钟", 
                            last_time.format("%H:%M:%S"),
                            wait_minutes);
                    } else {
                        info!("    上次: {} 前, 可以执行", last_time.format("%H:%M:%S"));
                    }
                } else {
                    info!("    上次: 未执行");
                }
                info!("");
            }
        }
        
        info!("调度器已启动");
        info!("");
    }

    async fn show_progress(&self) {
        let progress = self.day_task_manager.get_all_progress().await;
        info!("=== Task Progress ===");
        for (task_name, (executed, total)) in progress {
            if total > 0 {
                info!(
                    "Task {}: {}/{} days ({}%)",
                    task_name,
                    executed,
                    total,
                    (executed * 100) / total
                );
            } else {
                info!("Task {}: {} days (no limit)", task_name, executed);
            }
        }
        info!("==================");
    }

    #[allow(dead_code)]
    fn get_task_config(
        &self,
        config: &Config,
        task_config: &super::config::TaskConfig,
    ) -> (TimeSpec, TimeSpec, u32, u32, u32, Option<u32>) {
        // 解析开始时间：优先使用 start_time，否则使用 start_hour
        let start_time = if let Some(ref time_str) = task_config.start_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse task start_time '{}': {}, using start_hour", time_str, e);
                    let hour = task_config.start_hour.unwrap_or(9);
                    TimeSpec::from_hour(hour)
                }
            }
        } else if let Some(ref time_str) = config.schedule.start_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse global start_time '{}': {}, using start_hour", time_str, e);
                    let hour = task_config.start_hour
                        .unwrap_or_else(|| config.schedule.start_hour.unwrap_or(9));
                    TimeSpec::from_hour(hour)
                }
            }
        } else {
            let hour = task_config.start_hour
                .unwrap_or_else(|| config.schedule.start_hour.unwrap_or(9));
            TimeSpec::from_hour(hour)
        };
        
        // 解析结束时间：优先使用 end_time，否则使用 end_hour
        let end_time = if let Some(ref time_str) = task_config.end_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse task end_time '{}': {}, using end_hour", time_str, e);
                    let hour = task_config.end_hour.unwrap_or(18);
                    TimeSpec::from_hour(hour)
                }
            }
        } else if let Some(ref time_str) = config.schedule.end_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse global end_time '{}': {}, using end_hour", time_str, e);
                    let hour = task_config.end_hour
                        .unwrap_or_else(|| config.schedule.end_hour.unwrap_or(18));
                    TimeSpec::from_hour(hour)
                }
            }
        } else {
            let hour = task_config.end_hour
                .unwrap_or_else(|| config.schedule.end_hour.unwrap_or(18));
            TimeSpec::from_hour(hour)
        };
        
        let min_interval = task_config
            .min_interval_hours
            .unwrap_or_else(|| config.schedule.min_interval_hours.unwrap_or(2));
        
        // 处理固定执行次数（优先级最高）
        let fixed_executions = task_config
            .fixed_executions_per_day
            .or(config.schedule.fixed_executions_per_day);
        
        let (min_executions, max_executions) = if let Some(fixed) = fixed_executions {
            // 如果设置了固定次数，则 min 和 max 都设为该值
            (fixed, fixed)
        } else {
            let min = task_config
                .min_executions_per_day
                .unwrap_or_else(|| config.schedule.min_executions_per_day.unwrap_or(0));
            let max = task_config
                .max_executions_per_day
                .unwrap_or_else(|| config.schedule.max_executions_per_day.unwrap_or(3));
            (min, max)
        };

        (start_time, end_time, min_interval, min_executions, max_executions, fixed_executions)
    }

    fn get_account_config(
        &self,
        config: &Config,
        task_config: &super::config::TaskConfig,
        account: &super::config::AccountConfig,
    ) -> (TimeSpec, TimeSpec, u32, u32, u32, Option<u32>) {
        // 解析开始时间：优先级 账号 > 任务 > 全局
        let start_time = if let Some(ref time_str) = account.start_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse account start_time '{}': {}, fallback", time_str, e);
                    let hour = account.start_hour
                        .or(task_config.start_hour)
                        .or(config.schedule.start_hour)
                        .unwrap_or(9);
                    TimeSpec::from_hour(hour)
                }
            }
        } else if let Some(ref time_str) = task_config.start_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse task start_time '{}': {}, fallback", time_str, e);
                    let hour = account.start_hour
                        .or(task_config.start_hour)
                        .or(config.schedule.start_hour)
                        .unwrap_or(9);
                    TimeSpec::from_hour(hour)
                }
            }
        } else if let Some(ref time_str) = config.schedule.start_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse global start_time '{}': {}, fallback", time_str, e);
                    let hour = account.start_hour
                        .or(task_config.start_hour)
                        .or(config.schedule.start_hour)
                        .unwrap_or(9);
                    TimeSpec::from_hour(hour)
                }
            }
        } else {
            let hour = account.start_hour
                .or(task_config.start_hour)
                .or(config.schedule.start_hour)
                .unwrap_or(9);
            TimeSpec::from_hour(hour)
        };
        
        // 解析结束时间：优先级 账号 > 任务 > 全局
        let end_time = if let Some(ref time_str) = account.end_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse account end_time '{}': {}, fallback", time_str, e);
                    let hour = account.end_hour
                        .or(task_config.end_hour)
                        .or(config.schedule.end_hour)
                        .unwrap_or(18);
                    TimeSpec::from_hour(hour)
                }
            }
        } else if let Some(ref time_str) = task_config.end_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse task end_time '{}': {}, fallback", time_str, e);
                    let hour = account.end_hour
                        .or(task_config.end_hour)
                        .or(config.schedule.end_hour)
                        .unwrap_or(18);
                    TimeSpec::from_hour(hour)
                }
            }
        } else if let Some(ref time_str) = config.schedule.end_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => TimeSpec::new(h, m, s),
                Err(e) => {
                    warn!("Failed to parse global end_time '{}': {}, fallback", time_str, e);
                    let hour = account.end_hour
                        .or(task_config.end_hour)
                        .or(config.schedule.end_hour)
                        .unwrap_or(18);
                    TimeSpec::from_hour(hour)
                }
            }
        } else {
            let hour = account.end_hour
                .or(task_config.end_hour)
                .or(config.schedule.end_hour)
                .unwrap_or(18);
            TimeSpec::from_hour(hour)
        };
        
        let min_interval = account.min_interval_hours
            .or(task_config.min_interval_hours)
            .or(config.schedule.min_interval_hours)
            .unwrap_or(2);
        
        // 处理固定执行次数（优先级最高）
        let fixed_executions = account.fixed_executions_per_day
            .or(task_config.fixed_executions_per_day)
            .or(config.schedule.fixed_executions_per_day);
        
        let (min_executions, max_executions) = if let Some(fixed) = fixed_executions {
            (fixed, fixed)
        } else {
            let min = account.min_executions_per_day
                .or(task_config.min_executions_per_day)
                .or(config.schedule.min_executions_per_day)
                .unwrap_or(0);
            let max = account.max_executions_per_day
                .or(task_config.max_executions_per_day)
                .or(config.schedule.max_executions_per_day)
                .unwrap_or(3);
            (min, max)
        };

        (start_time, end_time, min_interval, min_executions, max_executions, fixed_executions)
    }

    #[allow(dead_code)]
    fn is_in_valid_time_range(&self, config: &Config, now: DateTime<Local>) -> bool {
        let start_time = self.parse_global_start_time(config);
        let end_time = self.parse_global_end_time(config);
        let current_time = now.time();
        
        current_time >= start_time.to_naive_time() && current_time < end_time.to_naive_time()
    }
    
    fn parse_global_start_time(&self, config: &Config) -> TimeSpec {
        if let Some(ref time_str) = config.schedule.start_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => return TimeSpec::new(h, m, s),
                Err(e) => warn!("Failed to parse global start_time: {}", e),
            }
        }
        let hour = config.schedule.start_hour.unwrap_or(9);
        TimeSpec::from_hour(hour)
    }
    
    fn parse_global_end_time(&self, config: &Config) -> TimeSpec {
        if let Some(ref time_str) = config.schedule.end_time {
            match parse_time_string(time_str) {
                Ok((h, m, s)) => return TimeSpec::new(h, m, s),
                Err(e) => warn!("Failed to parse global end_time: {}", e),
            }
        }
        let hour = config.schedule.end_hour.unwrap_or(18);
        TimeSpec::from_hour(hour)
    }

    #[allow(dead_code)]
    fn calculate_next_execution_time(
        &self,
        config: &Config,
        reference: DateTime<Local>,
    ) -> DateTime<Local> {
        let start_time_spec = self.parse_global_start_time(config);
        let end_time_spec = self.parse_global_end_time(config);
        let start_time = start_time_spec.to_naive_time();
        let end_time = end_time_spec.to_naive_time();

        let mut candidate_reference = reference;
        let mut candidate_date = candidate_reference.date_naive();

        loop {
            let window_start = Local
                .from_local_datetime(&NaiveDateTime::new(candidate_date, start_time))
                .single()
                .expect("failed to resolve window start time");
            let window_end = Local
                .from_local_datetime(&NaiveDateTime::new(candidate_date, end_time))
                .single()
                .expect("failed to resolve window end time");

            let mut earliest = window_start.max(candidate_reference);

            if let Some(interval_ready) = self.earliest_interval_after(config, earliest) {
                if interval_ready > earliest {
                    earliest = interval_ready;
                }
            }

            if earliest >= window_end {
                candidate_date = candidate_date.succ_opt().unwrap();
                candidate_reference = Local
                    .from_local_datetime(&NaiveDateTime::new(candidate_date, start_time))
                    .single()
                    .expect("failed to resolve next-day window start");
                continue;
            }

            let available_seconds = (window_end - earliest).num_seconds();
            if available_seconds <= 1 {
                return earliest;
            }

            let mut rng = rng();
            let offset_seconds = rng.random_range(1..available_seconds);
            return earliest + Duration::seconds(offset_seconds);
        }
    }

    #[allow(dead_code)]
    fn earliest_interval_after(
        &self,
        config: &Config,
        after: DateTime<Local>,
    ) -> Option<DateTime<Local>> {
        let mut earliest: Option<DateTime<Local>> = None;

        for task_config in &config.tasks {
            if !task_config.enabled {
                continue;
            }

            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }

                let account_key = Config::get_account_key(&task_config.name, &account.nickname);
                let (_, _, min_interval, _min_executions, max_executions, _fixed_executions) = 
                    self.get_account_config(config, task_config, account);

                if self
                    .execution_tracker
                    .has_reached_daily_limit(&account_key, max_executions)
                {
                    continue;
                }

                if let Some(next_allowed) = self
                    .execution_tracker
                    .next_allowed_time(&account_key, min_interval)
                {
                    if next_allowed <= after {
                        continue;
                    }

                    earliest = match earliest {
                        Some(existing) if existing <= next_allowed => Some(existing),
                        _ => Some(next_allowed),
                    };
                }
            }
        }

        earliest
    }

    /// 初始化每个账号的执行时间(为每个账号生成独立的随机时间)
    fn initialize_account_schedules(&mut self, config: &Config) {
        let now = Local::now();
        
        for task_config in &config.tasks {
            if !task_config.enabled {
                continue;
            }
            
            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }
                
                let account_key = Config::get_account_key(&task_config.name, &account.nickname);
                
                // 为每个账号生成独立的随机执行时间
                let next_time = self.calculate_next_execution_time_for_account(config, task_config, account, now);
                self.account_schedules.insert(account_key.clone(), next_time);
                
                info!("账号 {} 下次执行时间: {}", account_key, next_time.format("%Y-%m-%d %H:%M:%S"));
            }
        }
    }

    /// 为单个账号计算下次执行时间
    fn calculate_next_execution_time_for_account(
        &self,
        config: &Config,
        task_config: &super::config::TaskConfig,
        account: &super::config::AccountConfig,
        reference: DateTime<Local>,
    ) -> DateTime<Local> {
        let (start_time, end_time, _, _, _, _) = self.get_account_config(config, task_config, account);
        
        let start_naive = start_time.to_naive_time();
        let end_naive = end_time.to_naive_time();
        
        let mut candidate_date = reference.date_naive();
        let mut candidate_reference = reference;
        
        loop {
            let window_start = Local
                .from_local_datetime(&NaiveDateTime::new(candidate_date, start_naive))
                .single()
                .expect("failed to resolve window start time");
            let window_end = Local
                .from_local_datetime(&NaiveDateTime::new(candidate_date, end_naive))
                .single()
                .expect("failed to resolve window end time");
            
            let earliest = window_start.max(candidate_reference);
            
            if earliest >= window_end {
                candidate_date = candidate_date.succ_opt().unwrap();
                candidate_reference = Local
                    .from_local_datetime(&NaiveDateTime::new(candidate_date, start_naive))
                    .single()
                    .expect("failed to resolve next-day window start");
                continue;
            }
            
            let available_seconds = (window_end - earliest).num_seconds();
            if available_seconds <= 1 {
                return earliest;
            }
            
            let mut rng = rng();
            let offset_seconds = rng.random_range(1..available_seconds);
            return earliest + Duration::seconds(offset_seconds);
        }
    }

    /// 初始化所有账号的日志文件
    fn initialize_account_logs(&self, config: &Config) {
        let now = Local::now();
        let timestamp = now.format("%Y-%m-%d %H:%M:%S");
        
        for task_config in &config.tasks {
            if !task_config.enabled {
                continue;
            }
            
            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }
                
                let account_key = Config::get_account_key(&task_config.name, &account.nickname);
                
                // 记录程序启动信息
                self.account_logger.info(&account_key, &format!("========== 程序启动 {} ==========", timestamp));
                self.account_logger.info(&account_key, &format!("任务: {}", task_config.name));
                self.account_logger.info(&account_key, &format!("账号: {}", mask_email(&account.nickname)));
                
                // 记录配置信息
                let (start_time, end_time, min_interval, min_exec, max_exec, fixed_exec) = 
                    self.get_account_config(config, task_config, account);
                
                self.account_logger.info(&account_key, &format!("时间窗口: {} - {}", 
                    start_time.to_naive_time().format("%H:%M:%S"),
                    end_time.to_naive_time().format("%H:%M:%S")));
                
                if let Some(fixed) = fixed_exec {
                    self.account_logger.info(&account_key, &format!("每天固定执行: {} 次", fixed));
                } else {
                    self.account_logger.info(&account_key, &format!("每天执行次数: {} - {} 次", min_exec, max_exec));
                }
                
                self.account_logger.info(&account_key, &format!("最小间隔: {} 小时", min_interval));
                
                // 记录代理信息
                if let Some(proxy) = account.proxy.as_ref().or(task_config.proxy.as_ref()) {
                    self.account_logger.info(&account_key, &format!("代理: {}", mask_proxy_url(proxy)));
                }
                
                self.account_logger.info(&account_key, "初始化完成，等待执行");
            }
        }
    }

    /// 获取最早需要执行的账号时间
    #[allow(dead_code)]
    fn get_earliest_account_schedule(&self) -> Option<DateTime<Local>> {
        self.account_schedules.values().min().copied()
    }

    /// 更新指定账号的下次执行时间
    fn update_account_schedule(&mut self, account_key: &str, config: &Config) {
        // 找到对应的任务和账号配置
        for task_config in &config.tasks {
            if !task_config.enabled {
                continue;
            }
            
            for account in &task_config.accounts {
                if !account.enabled {
                    continue;
                }
                
                let key = Config::get_account_key(&task_config.name, &account.nickname);
                if key == account_key {
                    let next_time = self.calculate_next_execution_time_for_account(
                        config,
                        task_config,
                        account,
                        Local::now(),
                    );
                    self.account_schedules.insert(account_key.to_string(), next_time);
                    info!("账号 {} 更新下次执行时间: {}", account_key, next_time.format("%Y-%m-%d %H:%M:%S"));
                    return;
                }
            }
        }
    }
}
